#include <rtthread.h>
#include <rtdevice.h>

#include "lwip/sockets.h"

int sockfd;

#define SERVER_IP	"192.168.0.105"
//#define SERVER_IP	"127.0.0.1"

#define SERVER_PORT	1026

static void tcpclient_thread(void *arg)
{
	
	char *str;
	/*	连接者的主机信息 */
	struct sockaddr_in their_addr;	

	rt_thread_mdelay(5000);
	
	//创建socket
	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
	{
		/*	如果socket()调用出现错误则显示错误信息并退出 */
		perror("socket");
//		exit(1);
	}

	memset(&their_addr, 0, sizeof(their_addr));
	
	/*	主机字节顺序 */
	their_addr.sin_family = AF_INET;
	/*	网络字节顺序，短整型 */
	their_addr.sin_port = htons(SERVER_PORT);
	their_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
	
	//连接到服务器
	if(connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1)
	{
		/*	如果connect()建立连接错误，则显示出错误信息，退出 */
		perror("connect");
		//exit(1);
	}

	

	int ret;
	char recvbuf[512];
	char *buf = "hello! I'm client!";
	
	while(1)
	{
		//发送数据
		if((ret = send(sockfd, buf, strlen(buf) + 1, 0)) == -1)
		{
			perror("send : ");
		}

		rt_thread_mdelay(1000);

		memset(recvbuf, 0, sizeof(recvbuf));
		//接收数据
		if((ret = recv(sockfd, &recvbuf, sizeof(recvbuf), 0)) == -1){
			return ;
		}

		printf("recv :\r\n");
		printf("%s", recvbuf);
		printf("\r\n");

		rt_thread_mdelay(2000);
	}

	close(sockfd);

	
	return ;
}

void tcpclient_init(void)
{
	sys_thread_new("tcpecho_thread", tcpclient_thread, NULL, 5*1024, 3);
}
